/*
 *	Copyright © 2008 University of Houston
 *	All rights reserved.
 */
#include "util.h"

int 			Trace::verbosity = 0;
ostringstream	Trace::oss;

using namespace std;

//#ifdef __APPLE__
char* itoa(int value, char* result, int base)
{
	if (base < 2 || base > 16)
	{
		*result = 0;
		return result;
	}

	char* out = result;
	int quotient = value;

	do
	{
		*out = "0123456789abcdef"[ abs(quotient % base)];
		++out;
		quotient /= base;
	}
	while (quotient);

	// Only apply negative sign for base 10
	if (value < 0 && base == 10) *out++ = '-';

	reverse(result, out);
	*out = 0;
	return result;
}
//#endif

string itoa(int value, int base)
{
	// Allocate a 1KB buffer.  This never gets deallocated, but it is
	// only allocated once, so this is acceptable.
	static char *buf = NULL;
	if (buf == NULL)
		buf = new char[1024];

	return itoa(value, buf, base);
}

bool operator==(in_addr a,in_addr b)
{
	if (memcmp(&a, &b, sizeof(in_addr)) == 0)
		return true;
	return false;
}

bool operator==(sniff_tcp a, sniff_tcp b)
{
	if (a.th_sport 	== b.th_sport &&
			a.th_dport 	== b.th_dport &&
			a.th_seq    == b.th_seq &&
			a.th_ack 	== b.th_ack &&
			a.th_offx2	== b.th_offx2 &&
			a.th_flags 	== b.th_flags &&
			a.th_win	== b.th_win &&
			a.th_sum	== b.th_sum &&
			a.th_urp	== b.th_urp)
		return true;
	return false;
}

long double ttod(timeval t)
{
	long double d = t.tv_sec;
	d += t.tv_usec / (long double) 1000000;
	return d;
}


// Grats to http://senzee.blogspot.com/2006/05/c-formatting-stdstring.html
string format_arg_list(const char *fmt, va_list args)
{
	if (!fmt) return "";
	int   result = -1, length = 256;
	char *buffer = 0;
	while (result == -1)
	{
		if (buffer) delete [] buffer;
		buffer = new char [length + 1];
		memset(buffer, 0, length + 1);
		result = vsnprintf(buffer, length, fmt, args);
		length *= 2;
	}
	string s(buffer);
	delete [] buffer;
	return s;
};

string strprintf(const char *fmt, ...)
{
	va_list args;
	va_start(args, fmt);
	string s = format_arg_list(fmt, args);
	va_end(args);
	return s;
};

long strtol(const char* x)
{
	return strtol(x,NULL,10);
}
vector<string> stringSplit (string str, string delim)
{
	vector<string> v;
	u_int cutAt;
	while ((cutAt = str.find_first_of(delim)) != str.npos )
	{
		if (cutAt > 0)
		{
			v.push_back(str.substr(0,cutAt));
		}
		str = str.substr(cutAt+1);
	}
	if (str.length() > 0)
	{
		v.push_back(str);
	}
	return v;
}

